﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Weber.CS3280.Inventory.Model;

namespace Weber.CS3280.Inventory.Logic
{
	public class ItemCategoryController : INotifyPropertyChanged, ICloneable
	{
		private ItemCategory _category;
		private bool _isDirty;

		public ItemCategoryController()
			: this(new ItemCategory())
		{
			// Assume that the instance will be dirty for a new inventory item
			IsDirty = true;
		}

		public ItemCategoryController(Data.InventoryConnectionContext context, int categoryId)
		{

		}

		internal ItemCategoryController(ItemCategory item)
		{
			_category = item;
		}

		public int? ItemCategoryId
		{
			get { return _category.ItemCategoryId; }
			private set
			{
				_category.ItemCategoryId = value;
				NotifyPropertyChanged("ItemCategoryId");
			}
		}

		public string Name
		{
			get { return _category.Name; }
			set
			{
				if (_category.Name == value)
					return;
				_category.Name = value;
				NotifyPropertyChanged("Name");
			}
		}

		public bool IsDirty
		{
			get { return _isDirty; }
			set
			{
				if (_isDirty == value)
					return;
				_isDirty = value;
				// Let any subscribers know that the Cost changed
				NotifyPropertyChanged("IsDirty");
			}
		}

		public void Save(Data.InventoryConnectionContext context)
		{
			Data.ItemCategory category = new Data.ItemCategory(_category);

			category.Save(context);

			if (!ItemCategoryId.HasValue)
				ItemCategoryId = category.ID;
		}

		public event PropertyChangedEventHandler PropertyChanged;

		private void NotifyPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}

		public static ItemCategoryController[] GetCategories(Data.InventoryConnectionContext context)
		{
			// Retrieve the categories from the database
			return Data.ItemCategory.GetAllItemCategories(context)
				// and transform them to an Array of ItemCategoryController objects
				.Select(c => new ItemCategoryController(c))
				.ToArray();
		}

		object ICloneable.Clone()
		{
			return Clone();
		}

		/// <summary>
		/// Clones an ItemCategoryController
		/// </summary>
		/// <returns></returns>
		public ItemCategoryController Clone()
		{
			ItemCategory categoryCopy = new ItemCategory()
				{
					ItemCategoryId = ItemCategoryId,
					Name = Name,
				};

			ItemCategoryController copy = new ItemCategoryController(categoryCopy);

			copy.IsDirty = IsDirty;
			return copy;
		}
	}
}
